<script setup lang="ts">
import { useUserStore } from '@/stores/userStore.ts'
import { LogoutOutlined, UserOutlined } from '@ant-design/icons-vue'
import { userLogoutUsingPost } from '@/api/userController.ts'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import emitter from '@/eventBus.ts'

const router = useRouter()

const userStore = useUserStore()

// 个人中心
const goToUserCenter = () => {
  router.push('/user/center')
}

// 退出登录
const logout = async () => {
  const res = await userLogoutUsingPost()
  if (res.code === 200 && res.data) {
    message.success('操作成功')
    userStore.setLoginUser({
      userName: '未登录',
    })
    await router.push('/user/login')
    // 移除本地缓存
    localStorage.removeItem('user')
  } else {
    message.error(res.message)
  }
}

// 监听登录成功事件
emitter.on('loginSuccess', () => {
  userStore.fetchLoginUser()
})

// 监听登录用户信息更改事件
emitter.on('updateUserInfo', () => {
  userStore.fetchLoginUser()
})
</script>

<template>
  <div id="global-header">
    <a-row :wrap="false">
      <a-col flex="200px">
        <RouterLink to="/">
          <div class="title-bar">
            <img class="logo" alt="" src="../assets/new_logo.svg" />
            <div class="title">智享商城</div>
          </div>
        </RouterLink>
      </a-col>
      <a-col flex="auto" />
      <a-col flex="120px">
        <div class="user-login-state">
          <div v-if="userStore.loginUser.id">
            <a-dropdown>
              <a-space>
                <a-avatar :src="userStore.loginUser.userAvatar" />
                {{ userStore.loginUser.userName ?? '无名' }}
              </a-space>
              <template #overlay>
                <a-menu>
                  <a-menu-item @click="goToUserCenter">
                    <UserOutlined />
                    个人中心
                  </a-menu-item>
                  <a-menu-item @click="logout">
                    <LogoutOutlined />
                    退出登录
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </div>
          <div v-else>
            <a-button type="primary" href="/user/login">登录</a-button>
          </div>
        </div>
      </a-col>
    </a-row>
  </div>
</template>

<style scoped>
.title-bar {
  display: flex;
  align-items: center;
}

.title {
  color: black;
  font-size: 18px;
  margin-left: 16px;
}

.logo {
  height: 48px;
}
</style>
